﻿using System;
using System.Data;
using System.Web.UI.WebControls;
using System.Collections.Generic;
using Infragistics.WebUI.UltraWebGrid;
using System.IO;
using uMES.LeanManufacturing.ReportBusiness;
using uMES.LeanManufacturing.ParameterDTO;
using iTextSharp.text;
using iTextSharp.text.pdf;
using QRCoder;
using System.Drawing;
using System.Web.UI;

public partial class AssemblyRecordForm : ShopfloorPage, INormalReport
{
    const string QueryWhere = "AssemblyRecordForm";
    uMESCommonBusiness common = new uMESCommonBusiness();
    uMESAssemblyRecordBusiness bll = new uMESAssemblyRecordBusiness();

    protected void Page_Load(object sender, EventArgs e)
    {
        uMESMasterPage master = this.Master as uMESMasterPage;
        master.strNavigation = "当前位置：装配记录";
        master.strTitle = "装配记录";
        master.ChangeFrame(true);
        NormalReportControl normalCntrl = new NormalReportControl();
        normalCntrl.NormalOperation = this;
        normalCntrl.QueryWhere = QueryWhere;

        WebPanel = WebAsyncRefreshPanel1;

        if (!IsPostBack)
        {
            ClearMessage_PageLoad();
        }
    }

    #region 数据查询
    public Dictionary<string, string> GetQuery()
    {
        Dictionary<string, string> result = new Dictionary<string, string>();

        return result;
    }

    public void QueryData(Dictionary<string, string> query)
    {
        ClearMessage();

        try
        {
            //
        }
        catch (Exception ex)
        {
            DisplayMessage(ex.Message, false);
        }
    }

    public void ResetQuery()
    {
        Session[QueryWhere] = "";
        txtScan.Text = string.Empty;
    }
    #endregion

    #region 保存按钮
    protected void btnSave_Click(object sender, EventArgs e)
    {
        ClearMessage();

        try
        {
            if (wgMaterialList.Rows.Count == 0)
            {
                DisplayMessage("请输入物料列表", false);
                return;
            }

            string strSpecID = ddlSpec.SelectedValue;

            if (strSpecID == string.Empty)
            {
                DisplayMessage("请选择工序", false);
                return;
            }

            //判断总装配数量
            int intQty = 0;
            for (int i = 0; i < wgMaterialList.Rows.Count; i++)
            {
                string strQty = wgMaterialList.Rows[i].Cells.FromKey("Qty").Value.ToString();

                intQty += Convert.ToInt32(strQty);
            }

            int intAssemblyQty = Convert.ToInt32(txtAssemblyQty.Text);
            int intRequireQty = Convert.ToInt32(txtRequireQty.Text);

            if (intAssemblyQty + intQty > intRequireQty)
            {
                DisplayMessage("总装配数量不能大于需求数量", false);
                return;
            }

            string strContainerID = txtDispContainerID.Text;
            string strChildContainerID = txtProductNoID.Text;

            Dictionary<string, string> userInfo = Session["UserInfo"] as Dictionary<string, string>;
            string strEmployeeID = userInfo["EmployeeID"];

            for (int i = 0; i < wgMaterialList.Rows.Count; i++)
            {
                string strProductID = wgMaterialList.Rows[i].Cells.FromKey("ProductID").Value.ToString();
                string strQty = wgMaterialList.Rows[i].Cells.FromKey("Qty").Value.ToString();
                string strSerialNumber = wgMaterialList.Rows[i].Cells.FromKey("SerialNumber").Value.ToString();
                string strNotes = wgMaterialList.Rows[i].Cells.FromKey("Notes").Value.ToString();

                Dictionary<string, string> para = new Dictionary<string, string>();
                para.Add("ContainerID", strContainerID);
                para.Add("SpecID", strSpecID);
                para.Add("ChildContainerID", strChildContainerID);
                para.Add("ProductID", strProductID);
                para.Add("Qty", strQty);
                para.Add("UOMID", "");
                para.Add("SerialNumber", strSerialNumber);
                para.Add("Notes", strNotes);
                para.Add("EmployeeID", strEmployeeID);
                para.Add("AssemblyDate", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                para.Add("Status", "0");

                bll.AddAssemblyRecordInfo(para);
            }

            AfterSave();

            DisplayMessage("保存成功", true);
        }
        catch (Exception ex)
        {
            DisplayMessage(ex.Message, false);
        }
    }
    #endregion

    #region AfterSave
    protected void AfterSave()
    {
        wgMaterialList.Clear();
        txtProductNameDisp.Text = string.Empty;
        txtProductName.Text = string.Empty;
        txtProductID.Text = string.Empty;
        txtProductRevision.Text = string.Empty;
        txtDescription.Text = string.Empty;
        txtQty.Text = string.Empty;
        txtSerialNumber.Text = string.Empty;
        txtNotes.Text = string.Empty;

        ddlSpec_SelectedIndexChanged(null, null);
    }
    #endregion

    #region 查询批次信息
    protected void txtScan_TextChanged(object sender, EventArgs e)
    {
        ClearMessage();
        ClearDispData();

        try
        {
            string strScan = txtScan.Text.Trim();
            txtScan.Text = "";

            if (strScan != string.Empty)
            {
                DataTable DT = bll.GetContainerInfo(strScan);

                if (DT.Rows.Count == 0)
                {
                    DisplayMessage("无效的批次号", false);
                    return;
                }

                string strProcessNo = DT.Rows[0]["ProcessNo"].ToString();
                txtDispProcessNo.Text = strProcessNo;
                string strOprNo = DT.Rows[0]["OprNo"].ToString();
                txtDispOprNo.Text = strOprNo;
                string strContainerID = DT.Rows[0]["ContainerID"].ToString();
                txtDispContainerID.Text = strContainerID;
                Session["ParentContainerID"] = strContainerID;
                string strContainerName = DT.Rows[0]["ContainerName"].ToString();
                txtDispContainerName.Text = strContainerName;
                string strWorkflowID = DT.Rows[0]["WorkflowID"].ToString();
                txtDispWorkflowID.Text = strWorkflowID;
                string strProductID = DT.Rows[0]["ProductID"].ToString();
                txtDispProductID.Text = strProductID;
                string strProductName = DT.Rows[0]["ProductName"].ToString();
                txtDispProductName.Text = strProductName;
                string strDescription = DT.Rows[0]["Description"].ToString();
                txtDispDescription.Text = strDescription;
                string strQty = DT.Rows[0]["Qty"].ToString();
                txtDispQty.Text = strQty;
                string strChildCount = DT.Rows[0]["ChildCount"].ToString();
                txtChildCount.Text = strChildCount;

                string strPlannedStartDate = DT.Rows[0]["PlannedStartDate"].ToString();
                if (strPlannedStartDate != string.Empty)
                {
                    strPlannedStartDate = Convert.ToDateTime(strPlannedStartDate).ToString("yyyy-MM-dd");
                }
                txtDispPlannedStartDate.Text = strPlannedStartDate;

                string strPlannedCompletionDate = DT.Rows[0]["PlannedCompletionDate"].ToString();
                if (strPlannedCompletionDate != string.Empty)
                {
                    strPlannedCompletionDate = Convert.ToDateTime(strPlannedCompletionDate).ToString("yyyy-MM-dd");
                }
                txtDispPlannedCompletionDate.Text = strPlannedCompletionDate;

                GetSpec(strWorkflowID);
            }
        }
        catch (Exception ex)
        {
            DisplayMessage(ex.Message, false);
        }
    }
    #endregion

    #region 绑定工序列表
    protected void GetSpec(string strWorkflowID)
    {
        List<string> listWorkflowID = new List<string>();
        listWorkflowID.Add(strWorkflowID);

        DataTable DT = common.GetSpecListByWorkflowID(listWorkflowID);
        DT.Columns.Add("SpecNameDisp");

        foreach (DataRow row in DT.Rows)
        {
            string strSpecName = row["SpecName"].ToString();
            strSpecName = common.GetSpecNameWithOutProdName(strSpecName);
            row["SpecNameDisp"] = strSpecName;
        }

        ddlSpec.DataTextField = "SpecNameDisp";
        ddlSpec.DataValueField = "SpecID";
        ddlSpec.DataSource = DT;
        ddlSpec.DataBind();

        ddlSpec.Items.Insert(0, "");
    }
    #endregion

    #region 清空显示的批次信息
    protected void ClearDispData()
    {
        txtDispProcessNo.Text = string.Empty;
        txtDispOprNo.Text = string.Empty;
        txtDispContainerID.Text = string.Empty;
        txtDispContainerName.Text = string.Empty;
        txtDispWorkflowID.Text = string.Empty;
        txtDispProductName.Text = string.Empty;
        txtDispDescription.Text = string.Empty;
        txtDispQty.Text = string.Empty;
        txtDispPlannedStartDate.Text = string.Empty;
        txtDispPlannedCompletionDate.Text = string.Empty;

        ddlSpec.Items.Clear();
        txtProductNo.Text = string.Empty;

        wgItemList.Clear();
        wgAssemblyList.Clear();
        wgMaterialList.Clear();

        txtProductName.Text = string.Empty;
        txtQty.Text = string.Empty;
        txtSerialNumber.Text = string.Empty;
        txtNotes.Text = string.Empty;
    }
    #endregion

    protected void ClearMaterialInfo()
    {
        txtProductNameDisp.Text = string.Empty;
        txtQty.Text = string.Empty;
        txtAssemblyQty.Text = "0";
        txtRequireQty.Text = "0";
        txtSerialNumber.Text = string.Empty;
        txtNotes.Text = string.Empty;
        txtProductID.Text = string.Empty;
        txtProductName.Text = string.Empty;
        txtProductRevision.Text = string.Empty;
        txtDescription.Text = string.Empty;
    }

    #region 选择工序
    protected void ddlSpec_SelectedIndexChanged(object sender, EventArgs e)
    {
        ClearMessage();
        wgItemList.Clear();
        wgAssemblyList.Clear();
        ClearMaterialInfo();

        try
        {
            int intChildCount = Convert.ToInt32(txtChildCount.Text);
            string strProductNo = txtProductNo.Text;

            if (intChildCount > 0 && strProductNo == string.Empty)
            {
                DisplayMessage("请选择产品序号", true);
                return;
            }

            string strContainerID = txtDispContainerID.Text;
            string strProductID = txtDispProductID.Text;
            string strSpecID = ddlSpec.SelectedValue;

            string strProductNoID = string.Empty;
            int intQty = Convert.ToInt32(txtDispQty.Text);
            if (intChildCount > 0)
            {
                strProductNoID = txtProductNoID.Text;
                intQty = 1;
            }

            if (strProductID != string.Empty && strSpecID != string.Empty)
            {
                DataTable DT = bll.GetMaterialListByProductID(strProductID, strSpecID);
                DataTable dtAssembly = bll.GetAssemblyQty(strContainerID, strSpecID, strProductNoID);

                DT.Columns.Add("RequireQty");
                DT.Columns.Add("AssemblyQty");
                DT.Columns.Add("Qty");

                foreach (DataRow row in DT.Rows)
                {
                    int intQtyRequired = Convert.ToInt32(row["QtyRequired"].ToString());

                    string strProdID = row["ProductID"].ToString();
                    int intAssemblyQty = 0;
                    DataRow[] rows = dtAssembly.Select(string.Format("ProductID = '{0}'", strProdID));

                    if (rows.Length > 0)
                    {
                        intAssemblyQty = Convert.ToInt32(rows[0]["Qty"].ToString());
                    }

                    row["RequireQty"] = intQtyRequired * intQty;
                    row["AssemblyQty"] = intAssemblyQty;

                    if (intQtyRequired * intQty - intAssemblyQty >= 0)
                    {
                        row["Qty"] = intQtyRequired * intQty - intAssemblyQty;
                    }
                    else
                    {
                        row["Qty"] = "0";
                    }
                }

                wgItemList.DataSource = DT;
                wgItemList.DataBind();
            }
        }
        catch (Exception ex)
        {
            DisplayMessage(ex.Message, false);
        }
    }
    #endregion

    protected void wgItemList_ActiveRowChange(object sender, RowEventArgs e)
    {
        ClearMessage();

        try
        {
            string strContainerID = txtDispContainerID.Text;
            string strSpecID = ddlSpec.SelectedValue;
            string strProductNoID = txtProductNoID.Text;
            string strProductID = e.Row.Cells.FromKey("ProductID").Value.ToString();
            string strProductName = e.Row.Cells.FromKey("ProductName").Value.ToString();
            string strProductRevision = e.Row.Cells.FromKey("ProductRevision").Value.ToString();
            string strDescription = e.Row.Cells.FromKey("Description").Value.ToString();
            string strAssemblyQty = e.Row.Cells.FromKey("AssemblyQty").Value.ToString();
            string strRequireQty = e.Row.Cells.FromKey("RequireQty").Value.ToString();

            txtAssemblyQty.Text = strAssemblyQty;
            txtRequireQty.Text = strRequireQty;

            DataTable DT = bll.GetAssemblyList(strContainerID, strSpecID, strProductNoID, strProductID);

            wgAssemblyList.DataSource = DT;
            wgAssemblyList.DataBind();

            txtProductNameDisp.Text = strProductName;
            txtProductName.Text = strProductName;
            txtProductRevision.Text = strProductRevision;
            txtProductID.Text = strProductID;
            txtDescription.Text = strDescription;
        }
        catch (Exception ex)
        {
            DisplayMessage(ex.Message, false);
        }
    }

    #region 添加按钮
    protected void btnAdd_Click(object sender, EventArgs e)
    {
        ClearMessage();

        try
        {
            string strProductID = txtProductID.Text;
            if (strProductID == string.Empty)
            {
                DisplayMessage("请选择物料编码", false);
                return;
            }

            string strQty = txtQty.Text.Trim();

            if (strQty == string.Empty)
            {
                DisplayMessage("请输入数量", false);
                txtQty.Focus();
                return;
            }

            if (strQty.Contains("."))
            {
                DisplayMessage("数量应为整数", false);
                txtQty.Focus();
                return;
            }

            try
            {
                int intQty = Convert.ToInt32(strQty);

                if (intQty <= 0)
                {
                    DisplayMessage("数量应为正整数", false);
                    txtQty.Focus();
                    return;
                }
            }
            catch
            {
                DisplayMessage("数量应为数字", false);
                txtQty.Focus();
                return;
            }

            string strProductName = txtProductName.Text;
            string strDescription = txtDescription.Text;
            string strSerialNumber = txtSerialNumber.Text.Trim();
            string strNotes = txtNotes.Text.Trim();

            wgMaterialList.Rows.Add();
            wgMaterialList.Rows[wgMaterialList.Rows.Count - 1].Cells.FromKey("ProductID").Value = strProductID;
            wgMaterialList.Rows[wgMaterialList.Rows.Count - 1].Cells.FromKey("ProductName").Value = strProductName;
            wgMaterialList.Rows[wgMaterialList.Rows.Count - 1].Cells.FromKey("Description").Value = strDescription;
            wgMaterialList.Rows[wgMaterialList.Rows.Count - 1].Cells.FromKey("Qty").Value = strQty;
            wgMaterialList.Rows[wgMaterialList.Rows.Count - 1].Cells.FromKey("SerialNumber").Value = strSerialNumber;
            wgMaterialList.Rows[wgMaterialList.Rows.Count - 1].Cells.FromKey("Notes").Value = strNotes;

        }
        catch (Exception ex)
        {
            DisplayMessage(ex.Message, false);
        }
    }
    #endregion

    #region 物料列表操作
    protected void btnSelectAll_Click(object sender, EventArgs e)
    {
        ClearMessage();

        TemplatedColumn temCell = (TemplatedColumn)wgMaterialList.Columns.FromKey("ckSelect");

        for (int i = 0; i < temCell.CellItems.Count; i++)
        {
            Infragistics.WebUI.UltraWebGrid.CellItem cellItem = (Infragistics.WebUI.UltraWebGrid.CellItem)temCell.CellItems[i];
            CheckBox ckSelect = (CheckBox)cellItem.FindControl("ckSelect");

            ckSelect.Checked = true;
        }
    }

    protected void btnReverseSelect_Click(object sender, EventArgs e)
    {
        ClearMessage();

        TemplatedColumn temCell = (TemplatedColumn)wgMaterialList.Columns.FromKey("ckSelect");

        for (int i = 0; i < temCell.CellItems.Count; i++)
        {
            Infragistics.WebUI.UltraWebGrid.CellItem cellItem = (Infragistics.WebUI.UltraWebGrid.CellItem)temCell.CellItems[i];
            CheckBox ckSelect = (CheckBox)cellItem.FindControl("ckSelect");

            ckSelect.Checked = !ckSelect.Checked;
        }
    }

    protected void btnDel_Click(object sender, EventArgs e)
    {
        ClearMessage();

        TemplatedColumn temCell = (TemplatedColumn)wgMaterialList.Columns.FromKey("ckSelect");

        for (int i = temCell.CellItems.Count - 1; i >= 0; i--)
        {
            Infragistics.WebUI.UltraWebGrid.CellItem cellItem = (Infragistics.WebUI.UltraWebGrid.CellItem)temCell.CellItems[i];
            CheckBox ckSelect = (CheckBox)cellItem.FindControl("ckSelect");

            if (ckSelect.Checked == true)
            {
                wgMaterialList.Rows.RemoveAt(i);
            }
        }
    }
    #endregion
}